// src/app/join/[workspaceId]/page.tsx
'use client';
import React, {useEffect, useState} from 'react';
import Image from "next/image";
import VerificationInput from "react-verification-input";
import {Button} from "@/components/ui/button";
import Link from "next/link";
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {useGetWorkspaceInfo} from "@/features/workspaces/api/use-get-workspace-info";
import {Loader} from "lucide-react";
import {useJoin} from "@/features/workspaces/api/use-join";
import {toast} from "sonner";
import {useRouter} from "next/navigation";
import {cn} from "@/lib/utils";
import {useCurrentUser} from "@/hooks/use-current-user";


const Page = () => {
    const user = useCurrentUser()

    const workspaceId = useWorkspaceId();

    const [name, setName] = useState();
    const [isMember, setIsMember] = useState(false);

    const router = useRouter()
    useEffect(() => {
        // 已经是成员直接会工作区
        if (isMember) {
            router.push(`/social/workspace/${workspaceId}`);
        }
    }, [isMember, router, workspaceId]);

    useEffect(() => {
        useGetWorkspaceInfo({id: workspaceId as string})
            .then(({data, isLoading}) => {
                if (isLoading) return <div
                    className={`h-full flex items-center justify-center`}
                >
                    <Loader className={`size-6 animate-spin text-muted-foreground`}/>
                </div>
                setName(data.name)
                setIsMember(data.isMember)
            })
    }, [workspaceId]);

    const {mutate, isPending} = useJoin()
    const handleComplete = (value: string) => {
        mutate({
            workspaceId, joinCode: value, userId: user?.id!
        }, {
            onSuccess(id) {
                toast.success("Workspace joined")
                router.replace(`/social/workspace/${id}`)
            },
            onError(e) {
                // toast.error("Failed to join workspace")
                toast.error(e.message)
            }
        })
    }

    return (
        <div className={`h-full flex flex-col gap-y-8 items-center justify-center
        bg-white p-8 rounded-lg shadow-md`}>
            <Image src={'/logo.png'} alt={'logo'}
                   height={60} width={60}/>
            <div className={`flex flex-col gap-y-4 items-center justify-center max-w-md`}>
                <div className={`flex flex-col gap-y-2 items-center justify-center`}>
                    <h1 className={`text-2xl font-bold`}>
                        Join {name}
                    </h1>
                    <p className={`text-md text-muted-foreground`}>
                        Enter the workspace code to join
                    </p>
                </div>
                <VerificationInput
                    onComplete={handleComplete}
                    classNames={{
                        container: cn("flex gap-x-2", isPending && 'opacity-50 cursor-not-allow'),
                        character: `uppercase h-auto rounded-md border border-gray-300 text-lg
                        font-medium flex items-center justify-center text-gray-500`,
                        characterInactive: `bg-muted`,
                        characterSelected: `bg-white text-black`,
                        characterFilled: `bg-white text-black`
                    }}
                    autoFocus
                />
            </div>
            <div className={`flex gap-x-4`}>
                <Button asChild size={'lg'} variant={'outline'}>
                    <Link href={`/social`}>
                        Back to home
                    </Link>
                </Button>
            </div>
        </div>
    );
};

export default Page;